package com.tender.util;

import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description：摘要
 */
public class DigestsUtil {

    private static final String SHA1 = "SHA-1";

    private static final Integer ITERATIONS_512 = 512;
    private static final Integer ITERATIONS_1024 = 1024;

    /**
     * @param input 需要散列字符串
     * @param salt  盐字符串
     * @return
     * @Description sha1方法，利用明文密码 和 盐 来加密
     */
    public static String sha1(String input, String salt) {
        return sha1(input, salt, ITERATIONS_1024);
    }

    public static String sha1(String input, String salt, Integer iterations) {
        if (null == iterations || 0 == iterations) {
            iterations = ITERATIONS_1024;
        }
        return new SimpleHash(SHA1, input, salt, iterations).toString();
    }

    /**
     * @return
     * @Description 随机获得salt字符串
     */
    public static String generateSalt() {
        SecureRandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
        return randomNumberGenerator.nextBytes().toHex();
    }


    /**
     * @Description 生成密码字符密文和salt密文
     */
    public static Map<String, String> encryptPassword(String passwordPlain, Integer iterations) {
        Map<String, String> map = new HashMap<>();
        String salt = generateSalt();

        String password = sha1(passwordPlain, salt, iterations);
        map.put("salt", salt);
        map.put("password", password);
        map.put("passwordPlain", passwordPlain);
        return map;
    }
}
